import { Radio, Space } from 'antd-mobile'
import classNames from 'classnames'
import { useEffect, useState } from 'react'
import styles from './index.module.less'
import type Store from '../../store'
import type { Answer, Question, QuestionAnswer } from '../../interface'

const ChoiceIcon = () => {
    return <div className={styles.choiceIcon} />
}

const UnChoiceIcon = () => {
    return <div className={styles.unChoiceIcon} />
}

type Props = Pick<Store, 'updateAnswer'> & {
    question: Question
    answer?: Answer
}

export const SingleChoiceQuestion = (props: Props) => {
    const question = props.question.answer as QuestionAnswer[]

    const [value, setValue] = useState<string>('')

    useEffect(() => {
        setValue((props.answer?.result as string) ?? '')
    }, [props.answer])

    return (
        <div className={styles.singleChoiceBox}>
            <div className={styles.choiceBox}>
                <Radio.Group
                    value={value}
                    onChange={v => {
                        props.updateAnswer(props.question.id, String(v))
                    }}
                >
                    <Space direction="vertical" style={{ width: '100%' }}>
                        {question.map(item => {
                            return (
                                <div key={item.sole} className={styles.item}>
                                    <Radio
                                        value={item.sole}
                                        icon={checked =>
                                            checked ? <ChoiceIcon /> : <UnChoiceIcon />
                                        }
                                        className={classNames({
                                            [styles.choice]: value === item.sole,
                                        })}
                                    >
                                        {item.name}
                                    </Radio>
                                </div>
                            )
                        })}
                    </Space>
                </Radio.Group>
            </div>
        </div>
    )
}
